<script setup lang="tsx">
defineOptions({
  name: "sop"
});

import { ref, reactive, onMounted, onUnmounted, markRaw, getCurrentInstance, provide } from "vue";
import { querySopList, deleteSop } from "@/api/modules/operation";
import commonTable from "@/views/common/components/commonTable/index.vue";
import commonSearch from "@/views/common/components/commonSearch/index.vue";
import { Edit, Delete } from "@px-ui/icons-vue";
import { PxMessage } from "px-ui";
import { useUpdateDomHeight, useCancelUpdateDomHeight } from "@/hooks/useCommon";
import { useThrottleFn } from "@vueuse/core";
import { throttleDelay as delay } from "@/utils/constant";
import sopUpload from "./sopUpload.vue";
import sopCheckList from "./sopCheckList.vue";
import { useMessageBox } from "@/hooks/useCommon";
import checkLogs from "@/views/gas/components/checkLogs.vue";

interface Props {
  //  1 在供气瓶  2 返库气瓶  3 过期气瓶
  type: 1 | 2 | 3;
}

const props = withDefaults(defineProps<Props>(), { type: 1 });

provide("bottleType", props.type);

const gap = 88;
const defaultHeight = 606;
const objectModelTableRef = ref<HTMLElement | null>(null);
const commonTableRef = ref<CommonTable.TableRefType>(null);
const commonSearchRef = ref<CommonSearch.SearchFormRefType>(null);
const scrollbarHeight = ref<number>(defaultHeight);
// taskType 任务类型 (1-气瓶,2-酸桶,3-槽车充填)
const sopCheckListParams = reactive<{ templateId: string; taskType: number }>({
  templateId: "",
  taskType: 1
});

const searchOption = ref<Array<CommonSearch.SearchOption>>([
  {
    label: "CheckList名称",
    key: "fileName",
    value: "",
    type: "input",
    placeholder: "请输入CheckList名称",
    span: 5
  },
  {
    label: "关联气体名称",
    key: "gasName",
    value: "",
    type: "input",
    placeholder: "请输入关联气体名称",
    span: 5
  }
]);

const tableCloumns = ref<Array<CommonTable.TableCloumnsType>>([
  {
    label: "CheckList",
    prop: "fileName",
    width: 180,
    render({ row }: any) {
      const { id: templateId = "", fileName = "" } = row;
      const styleFn = () => {
        return {
          color: "var(--px-color-primary)",
          cursor: "pointer"
        };
      };
      const clickHandler = () => {
        sopCheckListParams.templateId = templateId;
        sopCheckListVisible.value = true;
      };
      return () => (
        <div style={{ width: "100%", height: "100%", display: "flex" }}>
          <div style={styleFn()} onClick={clickHandler}>
            {fileName || "--"}
          </div>
        </div>
      );
    }
  },
  {
    label: "关联气体",
    prop: "gasName",
    width: 180
  },
  {
    label: "描述",
    prop: "remark",
    width: 180
  }
]);

let defaultParams: any = {
  // 任务类型(1:气瓶 2：酸桶)
  taskType: 1
};

const params = ref<any>({});
// 弹框类型 add 新增   edit 编辑
const sopUploadType = ref<"add" | "edit">("add");
const sopUploadId = ref<string>("");
const sopUploadVisible = ref<boolean>(false);
const sopCheckListVisible = ref<boolean>(false);
const checkLogsDialogVisible = ref<boolean>(false);

const operationOptions: Array<CommonTable.operationOptionItemType> = [
  {
    content: "编辑",
    auth: "GAS_OPERATION_BOTTLEMANAGE_LEDGERMANAGE_SOP_EDITBTN",
    icon: markRaw(Edit),
    click: (scope: any) => edit(scope)
  },
  {
    content: "删除",
    auth: "GAS_OPERATION_BOTTLEMANAGE_LEDGERMANAGE_SOP_DELETEBTN",
    icon: markRaw(Delete),
    type: "danger",
    click: (scope: any) => del(scope)
  }
];

let currentParams: any = {};

const getRowKey = row => {
  return row.id;
};

const sortChangeHandler = ({ column, order }: CommonTable.SortParams) => {
  const { property: orderBy = "" } = column;
  // ascending  descending
  const isAsc = order === "ascending" ? true : order === "descending" ? false : true;
  currentParams["orderBy"] = orderBy;
  currentParams["isAsc"] = isAsc;
  if (!order) {
    currentParams.orderBy && delete currentParams.orderBy;
    currentParams.isAsc && delete currentParams.isAsc;
  }
  updateParams();
};

const updateParams = () => {
  params.value = { ...defaultParams, ...currentParams };
};

const submitSearchFormHandler = (form: any) => {
  currentParams = { ...currentParams, ...form };
  updateParams();
};

const resetSearchFormHandler = () => {
  currentParams = {};
  updateParams();
};

const uploadFn = () => {
  sopUploadId.value = "";
  sopUploadType.value = "add";
  sopUploadVisible.value = true;
};

const { proxy }: any = getCurrentInstance();

const downloadFn = useThrottleFn(async () => {
  const url = "/operation/api/v1/gas/taskChecklistTemplate/downloadTemplate";
  const form = new FormData();
  //  taskType  任务类型(1：气瓶， 2：酸桶)
  form.append("taskType", "1");
  proxy.download("post", url, form);
}, delay);

const edit = scope => {
  const {
    row: { id = "" }
  } = scope;
  sopUploadId.value = id;
  sopUploadType.value = "edit";
  sopUploadVisible.value = true;
};

const del = async scope => {
  const {
    row: { fileName: labelName = "", id = "" }
  } = scope;
  const msg = `确定要删除SOP ${labelName}吗？`;
  useMessageBox("delete", msg, async () => {
    const params = { labelName, id };
    await deleteSop(params);
    PxMessage.success("删除成功！");
    commonTableRef.value.queryTableData();
  });
};

const checkLogsFn = () => {
  checkLogsDialogVisible.value = true;
};

const submitHandler = async () => {
  const message = sopUploadType.value === "add" ? "上传成功" : "编辑成功";
  PxMessage.success(message);
  await commonTableRef.value.queryTableData(null, true);
};

onMounted(async () => {
  await useUpdateDomHeight(scrollbarHeight, objectModelTableRef, gap, defaultHeight);
});

onUnmounted(() => useCancelUpdateDomHeight());
</script>

<template>
  <div class="all-orders">
    <div class="all-orders-search">
      <commonSearch
        v-if="searchOption?.length"
        ref="commonSearchRef"
        :row-num="4"
        :operation-span="3"
        :option="searchOption"
        @submit="submitSearchFormHandler"
        @reset="resetSearchFormHandler"
      />
    </div>
    <div class="all-orders-btns">
      <px-button v-has="'GAS_OPERATION_BOTTLEMANAGE_LEDGERMANAGE_SOP_UPLOADBTN'" type="primary" @click="uploadFn">上传</px-button>
      <px-button v-has="'GAS_OPERATION_BOTTLEMANAGE_LEDGERMANAGE_SOP_DOWNLOADBTN'" type="primary" plain @click="downloadFn">模板下载</px-button>
      <px-button v-has="'GAS_OPERATION_BOTTLEMANAGE_LEDGERMANAGE_SOP_CHECKLOGS_BTN'" type="primary" plain @click="checkLogsFn">查看日志</px-button>
    </div>
    <div ref="objectModelTableRef" class="all-orders-table">
      <commonTable
        ref="commonTableRef"
        indexNeed
        :operationOptions="operationOptions"
        :tableCloumns="tableCloumns"
        :height="scrollbarHeight"
        :row-key="getRowKey"
        :axiosApi="querySopList"
        :params="params"
        @sort-change="sortChangeHandler"
      />
    </div>
    <sopUpload v-if="sopUploadVisible" :id="sopUploadId" v-model="sopUploadVisible" :type="sopUploadType" @submit="submitHandler" />
    <sopCheckList v-if="sopCheckListVisible" v-model="sopCheckListVisible" :params="sopCheckListParams" />
    <checkLogs v-if="checkLogsDialogVisible" v-model="checkLogsDialogVisible" type="工单作业SOP管理" title="CheckList管理" />
  </div>
</template>

<style lang="scss" scoped>
.all-orders {
  width: 100%;
  background-color: #fff;

  .all-orders-search {
    width: 100%;
  }

  .all-orders-btns {
    display: flex;
    align-items: center;
    margin-top: 16px;
  }

  .all-orders-table {
    margin-top: 16px;
  }
}
</style>
